package com.tianma315.core.agent.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;

import com.tianma315.core.agent.dao.AgentAddressDao;
import com.tianma315.core.agent.domain.AgentAddressDO;
import com.tianma315.core.agent.service.AgentAddressService;
import com.tianma315.core.common.base.CoreServiceImpl;
import com.tianma315.core.common.exception.IFastException;
import com.tianma315.core.common.type.EnumErrorCode;
import org.springframework.stereotype.Service;



import java.util.Calendar;

/**
 * 
 * <pre>
 * 经销商地址
 * </pre>
 * <small> 2019-08-02 11:22:31 | Wen</small>
 */
@Service
public class AgentAddressServiceImpl extends CoreServiceImpl<AgentAddressDao, AgentAddressDO> implements AgentAddressService {

    @Override
    public Page<AgentAddressDO> getAgentAddressDOPage(Integer pageNumber, Integer pageSize, AgentAddressDO agentAddressDTO) {
        Page<AgentAddressDO> page = new Page<>(pageNumber,pageSize);
        EntityWrapper<AgentAddressDO> wrapper = new EntityWrapper<>();
        wrapper.eq("agent_id",agentAddressDTO.getAgentId());
        wrapper.ne("status",2);
        page = selectPage(page,wrapper);
        int total = selectCount(wrapper);
        page.setTotal(total);
        return page;
    }

    @Override
    public Boolean addAgentAddressDO(AgentAddressDO agentAddressDO) {
        agentAddressDO.setStatus(0);//0是非默认地址
        agentAddressDO.setCreateDate(Calendar.getInstance().getTime());
        Boolean result = insert(agentAddressDO);
        return result;
    }

    @Override
    public Boolean deleteAgentAddressDO(Long id, Integer status) {
        //状态为1时是默认地址，默认地址不能修改状态
        if (status.equals(1)){
            throw new IFastException(EnumErrorCode.defaultAddressNotDel.getCodeStr());
        }else{
            AgentAddressDO agentAddressDO = new AgentAddressDO();
            agentAddressDO.setStatus(2);
            agentAddressDO.setAddressId(id);
            Boolean result = updateById(agentAddressDO);
            return result;
        }
    }

    @Override
    public Boolean updateStatus(Long id, Long agentId) {
        // 把默认地址设置为非默认地址
        EntityWrapper<AgentAddressDO> wrapper = new EntityWrapper();
        wrapper.eq("agent_id",agentId);
        wrapper.eq("status",1);
        AgentAddressDO agentAddressDO = new AgentAddressDO();
        agentAddressDO.setStatus(0);
        update(agentAddressDO,wrapper);

        //把当前记录设置为默认地址
        AgentAddressDO newAgentAddress = new AgentAddressDO();
        newAgentAddress.setStatus(1);
        newAgentAddress.setAddressId(id);
        Boolean result = updateById(newAgentAddress);
        return result;
    }
}
